package com.bl.student.service.biz.task.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.common.utils.ListUtils;
import com.bl.student.common.utils.UUIDUtils;
import com.bl.student.common.enums.PointType;
import com.bl.student.dao.model.PointEntity;
import com.bl.student.dao.model.*;
import com.bl.student.dao.redis.model.UserInfo;
import com.bl.student.dao.repository.*;
import com.bl.student.service.biz.comment.CommentService;
import com.bl.student.service.vo.DelBody;
import com.bl.student.service.vo.DelListBody;
import com.bl.student.service.vo.comment.CommentAddVo;
import com.bl.student.service.vo.confirm.ConfirmAddVo;
import com.bl.student.service.vo.confirm.ConfirmListVo;
import com.bl.student.service.vo.confirm.ConfirmRefundVo;
import com.bl.student.service.vo.task.*;
import com.bl.student.service.biz.apply.ApplyService;
import com.bl.student.service.biz.task.TaskService;
import com.bl.student.service.biz.user.UserService;
import com.bl.student.service.vo.user.UserSimpleInfoVo;
import com.bl.student.service.biz.point.PointService;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * Created by liangweikang on 18/7/20.
 */
@Service
@Log4j2
public class TaskServiceImpl implements TaskService {

    @Autowired
    TaskRepository taskRepository;

    @Autowired
    ApplyRepository applyRepository;

    @Autowired
    UserService userService;

    @Autowired
    ApplyService applyService;

    @Autowired
    ConfirmRepository confirmRepository;

    @Autowired
    CommentService commentService;

    @Autowired
    TeacherRepository teacherRepository;

    @Autowired
    PointRepository pointRepository;

    @Autowired
    CommentRepository commentRepository;

    @Autowired
    PointService pointService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    PercentRepository percentRepository;


    /**
     * 甲方任务列表
     * @param partyaid
     * @param status
     * @param pageable
     * @return
     */
    @Override
    public TaskListVo getTaskListsPartya(String partyaid, String status, Pageable pageable) {
        TaskListVo taskListVo = new TaskListVo();
        Page<TaskEntity> taskEntities;
        List<TaskVo> taskVoList = new ArrayList<>();
        if ("ALL".equals(status)) {
            taskEntities = taskRepository.findByPartyaIdOrderByCreateTimeDesc(partyaid,pageable);
        } else {
            taskEntities = taskRepository.findByPartyaIdAndStatusOrderByCreateTimeDesc(partyaid,status,pageable);
        }
        taskListVo.setTotalCount(taskEntities.getTotalElements());
        for (TaskEntity taskEntity : taskEntities) {
            TaskVo taskVo = new TaskVo();
            taskVo.setTaskEntity(taskEntity);
            UserSimpleInfoVo partaSimpleInfoVo = userService.getUserById(taskEntity.getPartyaId(), "PARTYA");
            taskVo.setPartaSimpleInfoVo(partaSimpleInfoVo);

//            if (taskEntity.getPartybId() != null) {
//                UserSimpleInfoVo partbSimpleInfoVo = userService.getUserById(taskEntity.getPartybId(), "PARTYB");
//                taskVo.setPartbSimpleInfoVo(partbSimpleInfoVo);
//            }

            // 多个乙方，多个乙方信息
            taskVo.setPartbSimpleInfoVoList(applyService.getApplyListAgree(taskEntity.getId()));

            List<ConfirmEntity> confirmEntities = confirmRepository.findByTaskIdOrderByCreateTimeDesc(taskEntity.getId());
            if (confirmEntities != null && confirmEntities.size() > 0) {
                taskVo.setConfirmEntity(ListUtils.getFirst(confirmEntities));
            }

            // 多个乙方,多个确认完成
            taskVo.setConfirmEntities(confirmEntities);

            taskVoList.add(taskVo);
        }
        taskListVo.setList(taskVoList);

        return taskListVo;
    }

    /**
     * 乙方任务列表
     * @param partybid
     * @param status
     * @param pageable
     * @return
     */
    @Override
    public TaskListVo getTaskListsPartyb(String partybid, String status, Pageable pageable) {
        TaskListVo taskListVo = new TaskListVo();
        Page<TaskEntity> taskEntities;
        List<TaskVo> taskVoList = new ArrayList<>();
        if ("ALL".equals(status)) {
            taskEntities = taskRepository.findByPartybIdOrderByCreateTimeDesc(partybid,pageable);
        } else if ("PRE".equals(status)) {
            List<ApplyEntity> applyEntities = applyRepository.findByPartybId(partybid);
            for (ApplyEntity applyEntity : applyEntities) {
                TaskVo taskVo = new TaskVo();
                TaskEntity taskEntity = taskRepository.findOne(applyEntity.getTaskId());
                if (taskEntity.getStatus().equals("PRE")) {
                    taskVo.setTaskEntity(taskEntity);
                    UserSimpleInfoVo partaSimpleInfoVo = userService.getUserById(taskEntity.getPartyaId(), "PARTYA");
                    taskVo.setPartaSimpleInfoVo(partaSimpleInfoVo);
                    UserSimpleInfoVo partbSimpleInfoVo = userService.getUserById(partybid, "PARTYB");
                    taskVo.setPartbSimpleInfoVo(partbSimpleInfoVo);
                    taskVoList.add(taskVo);
                }
            }
            taskListVo.setTotalCount(applyEntities.size());
        } else {
            List<ApplyEntity> applyEntities = applyService.getApplyListsByPartybAndStatus(partybid, 1);
            for (ApplyEntity applyEntity : applyEntities) {
                TaskVo taskVo = new TaskVo();
                TaskEntity taskEntity = taskRepository.findOne(applyEntity.getTaskId());
                if (taskEntity.getStatus().equals(status)) {
                    taskVo.setTaskEntity(taskEntity);
                    UserSimpleInfoVo partaSimpleInfoVo = userService.getUserById(taskEntity.getPartyaId(), "PARTYA");
                    taskVo.setPartaSimpleInfoVo(partaSimpleInfoVo);
                    UserSimpleInfoVo partbSimpleInfoVo = userService.getUserById(partybid, "PARTYB");
                    taskVo.setPartbSimpleInfoVo(partbSimpleInfoVo);
                    taskVoList.add(taskVo);
                }
            }
            taskListVo.setTotalCount(applyEntities.size());
//            taskEntities = taskRepository.findByPartybIdAndStatusOrderByCreateTimeDesc(partybid,status,pageable);
//            taskListVo.setTotalCount(taskEntities.getTotalElements());
//            for (TaskEntity taskEntity : taskEntities) {
//                TaskVo taskVo = new TaskVo();
//                taskVo.setTaskEntity(taskEntity);
//                UserSimpleInfoVo partaSimpleInfoVo = userService.getUserById(taskEntity.getPartyaId(), "PARTYA");
//                taskVo.setPartaSimpleInfoVo(partaSimpleInfoVo);
//                UserSimpleInfoVo partbSimpleInfoVo = userService.getUserById(partybid, "PARTYB");
//                taskVo.setPartbSimpleInfoVo(partbSimpleInfoVo);
//                taskVoList.add(taskVo);
//            }
        }
        taskListVo.setList(taskVoList);
        return taskListVo;
    }

    /**
     * 多条件筛选查询
     * @return
     */
    @Override
    public TaskListVo getTaskListsMulti(String class3, String class2, String class1, String online, String sex, String price,
                                        String language, String grade, String college, String type, String star, String location,
                                        String time, String count, String role, String chinese, String env, String t_sex,
                                        Pageable pageable, String status, double longitude, double latitude, String buyType, String runType, String sortType){
        if (class3 == null || class3.equals("")) {
            class3 = null;
        }

        if (class2 == null || class2.equals("")) {
            class2 = null;
        }

        if (class1 == null || class1.equals("")) {
            class1 = null;
        }

        if (online == null || online.equals("")) {
            online = null;
        }

        if (sex == null || sex.equals("")) {
            sex = null;
        }

        if (price == null || price.equals("")) {
            price = null;
        }

        if (language == null || language.equals("")) {
            language = null;
        }

        if (grade == null || grade.equals("")) {
            grade = null;
        }

        if (college == null || college.equals("")) {
            college = null;
        }

        if (type == null || type.equals("")) {
            type = null;
        }

        if (star == null || star.equals("")) {
            star = null;
        }

        if (location == null || location.equals("")) {
            location = null;
        }

        if (time == null || time.equals("")) {
            time = null;
        }

        if (count == null || count.equals("")) {
            count = null;
        }

        if (role == null || role.equals("")) {
            role = null;
        }

        if (chinese == null || chinese.equals("")) {
            chinese = null;
        }

        if (env == null || env.equals("")) {
            env = null;
        }

        if (t_sex == null || t_sex.equals("")) {
            t_sex = null;
        }

        if (status == null || status.equals("")) {
            status = null;
        }

        if (buyType == null || buyType.equals("")) {
            buyType = null;
        }

        if (runType == null || runType.equals("")) {
            runType = null;
        }

        TaskListVo taskListVo = new TaskListVo();
        List<TaskVo> taskVoList = new ArrayList<>();

        if(sortType.equals("time")) { //时间排序
            List <TaskEntity> taskEntities;
            if(class3 == null && class2 == null && class1 == null && online == null&& sex == null&& price == null&& language == null&& grade == null&& college == null&& type == null&& star == null&& location == null&& time == null&& count == null && role == null && chinese == null && env == null
                    && t_sex == null && status == null && runType == null && buyType == null) {
                taskEntities = taskRepository.findAll();
            } else {
                taskEntities = taskRepository.findMultListAll(class3, class2, class1, online, sex, price, language, grade, college, type, star, location, time, count, role, chinese, env, t_sex, status, buyType, runType);
            }

            for (TaskEntity taskEntity : taskEntities) {
                TaskVo taskVo = new TaskVo();
                taskVo.setTaskEntity(taskEntity);
                UserSimpleInfoVo partaSimpleInfoVo = userService.getUserById(taskEntity.getPartyaId(), "PARTYA");
                taskVo.setPartaSimpleInfoVo(partaSimpleInfoVo);
//                if (taskEntity.getPartybId() != null) {
//                    UserSimpleInfoVo partbSimpleInfoVo = userService.getUserById(taskEntity.getPartybId(), "PARTYB");
//                    taskVo.setPartbSimpleInfoVo(partbSimpleInfoVo);
//                }

                //计算距离
                if (taskEntity.getLongitude() == 0 && taskEntity.getLatitude() == 0) {
                    taskVo.setDistance("-1");
                } else {
                    String distance = algorithm(taskEntity.getLongitude(), taskEntity.getLatitude(), longitude, latitude);
                    taskVo.setDistance(distance);
                }
                taskVoList.add(taskVo);
            }
            //对taskVoList根据CreateTime手动排序
            taskVoList.sort(new Comparator<TaskVo>() {
                @Override
                public int compare(TaskVo o1, TaskVo o2) {
                    TaskEntity taskEntity1= o1.getTaskEntity();
                    TaskEntity taskEntity2= o2.getTaskEntity();
                    Date createTime1 = taskEntity1.getCreateTime();
                    Date createTime2 = taskEntity2.getCreateTime();
                    return createTime2.compareTo(createTime1);
                }
            });
            //手动分页
            List<TaskVo> taskVoList0 = new ArrayList<>();
            taskVoList0 = pageBySubList(taskVoList, (int)pageable.getPageSize(), (int)pageable.getPageNumber());
            taskListVo.setTotalCount(taskEntities.size());
            taskListVo.setList(taskVoList0);
        } else if(sortType.equals("distance")){ //距离排序
            List<TaskEntity> taskEntities1 = new ArrayList<>();
            if(class3 == null && class2 == null && class1 == null && online == null&& sex == null&& price == null&& language == null&& grade == null&& college == null&& type == null&& star == null&& location == null&& time == null&& count == null && role == null && chinese == null && env == null
                    && t_sex == null && status == null && runType == null && buyType == null) {
                taskEntities1 = taskRepository.findAll();
            } else {
                taskEntities1 = taskRepository.findMultListAll(class3, class2, class1, online, sex, price, language, grade, college, type, star, location, time, count, role, chinese, env, t_sex, status, buyType, runType);
            }
            for(TaskEntity taskEntity:taskEntities1){
                TaskVo taskVo = new TaskVo();
                taskVo.setTaskEntity(taskEntity);
                UserSimpleInfoVo partaSimpleInfoVo = userService.getUserById(taskEntity.getPartyaId(), "PARTYA");
                taskVo.setPartaSimpleInfoVo(partaSimpleInfoVo);
//                if (taskEntity.getPartybId() != null) {
//                    UserSimpleInfoVo partbSimpleInfoVo = userService.getUserById(taskEntity.getPartybId(), "PARTYB");
//                    taskVo.setPartbSimpleInfoVo(partbSimpleInfoVo);
//                }
                //计算距离
                //计算距离
                if (taskEntity.getLongitude() == 0 && taskEntity.getLatitude() == 0) {
                    taskVo.setDistance("-1");
                } else {
                    String distance = algorithm(taskEntity.getLongitude(), taskEntity.getLatitude(), longitude, latitude);
                    taskVo.setDistance(distance);
                }
                taskVoList.add(taskVo);
            }

            List<TaskVo> taskVosDistance = new ArrayList<>();
            List<TaskVo> taskVosNoDistance = new ArrayList<>();
            List<TaskVo> newTaskVoList = new ArrayList<>();

            for (TaskVo taskVo : taskVoList) {
                if (taskVo.getDistance().equals("-1")) {
                    taskVosNoDistance.add(taskVo);
                } else {
                    taskVosDistance.add(taskVo);
                }
            }

            //对taskVoList根据距离排序
            taskVosDistance.sort(new Comparator<TaskVo>() {
                @Override
                public int compare(TaskVo o1, TaskVo o2) {
                    float f1 = Float.parseFloat(o1.distance);
                    float f2 = Float.parseFloat(o2.distance);
                    return (int)f1 - (int)f2;
                }
            });

            newTaskVoList.addAll(taskVosDistance);
            newTaskVoList.addAll(taskVosNoDistance);

            //手动分页
            List<TaskVo> taskVoList1 = new ArrayList<>();
            taskVoList1 = pageBySubList(newTaskVoList, (int)pageable.getPageSize(), (int)pageable.getPageNumber());
            taskListVo.setTotalCount(taskEntities1.size());
            taskListVo.setList(taskVoList1);

        } else if(sortType.equals("grade")) { //评分排序
            List<TaskEntity> taskEntities2 = new ArrayList<>();
            if(class3 == null && class2 == null && class1 == null && online == null&& sex == null&& price == null&& language == null&& grade == null&& college == null&& type == null&& star == null&& location == null&& time == null&& count == null && role == null && chinese == null && env == null
                    && t_sex == null && status == null && runType == null && buyType == null) {
                taskEntities2 = taskRepository.findAll();
            } else {
                taskEntities2 = taskRepository.findMultListAll(class3, class2, class1, online, sex, price, language, grade, college, type, star, location, time, count, role, chinese, env, t_sex, status, buyType, runType);
            }
            for(TaskEntity taskEntity:taskEntities2) {
                TaskVo taskVo = new TaskVo();
                taskVo.setTaskEntity(taskEntity);
                UserSimpleInfoVo partaSimpleInfoVo = userService.getUserById(taskEntity.getPartyaId(), "PARTYA");
                taskVo.setPartaSimpleInfoVo(partaSimpleInfoVo);
                //设置评分
                taskVo.setGrade(partaSimpleInfoVo.getGrade());
//                if (taskEntity.getPartybId() != null) {
//                    UserSimpleInfoVo partbSimpleInfoVo = userService.getUserById(taskEntity.getPartybId(), "PARTYB");
//                    taskVo.setPartbSimpleInfoVo(partbSimpleInfoVo);
//                }
                //计算距离
                //计算距离
                if (taskEntity.getLongitude() == 0 && taskEntity.getLatitude() == 0) {
                    taskVo.setDistance("-1");
                } else {
                    String distance = algorithm(taskEntity.getLongitude(), taskEntity.getLatitude(), longitude, latitude);
                    taskVo.setDistance(distance);
                }
                taskVoList.add(taskVo);
            }
            //对taskVoList根据user的grade进行排序
            taskVoList.sort(new Comparator<TaskVo>() {
                @Override
                public int compare(TaskVo o1, TaskVo o2) {
                    Double grade1 = o1.getGrade();
                    Double grade2 = o2.getGrade();
                    return  grade2.intValue() - grade1.intValue();
                }
            });
            //手动分页
            List<TaskVo> taskVoList2 = new ArrayList<>();
            taskVoList2 = pageBySubList(taskVoList, (int)pageable.getPageSize(), (int)pageable.getPageNumber());
            taskListVo.setTotalCount(taskEntities2.size());
            taskListVo.setList(taskVoList2);

        }

        return  taskListVo;
    }

    @Override
    public void confirm(ConfirmAddVo confirmAddVo, String userId) {

        TaskEntity taskEntity = taskRepository.findOne(confirmAddVo.getTaskId());
//        if (!"ONLINE".equals(taskEntity.getStatus())) {
//            throw new CommonServiceException(ApiResponseCode.PERMISSION_DENIED.getCode(), "状态不是进行中，无法确认完成");
//        }
        ConfirmEntity confirmEntity = new ConfirmEntity();
        BeanUtils.copyProperties(confirmAddVo, confirmEntity);
        confirmEntity.setId(UUIDUtils.getUUID());
        confirmEntity.setPartybId(userId);
        confirmEntity.setRefused(0);
        confirmEntity.setCreateTime(new Date());
        confirmEntity.setUpdateTime(new Date());
        confirmRepository.save(confirmEntity);
        // 修改task状态
        taskEntity.setStatus("BFINISH");
        taskEntity.setUpdateTime(new Date());
        taskRepository.save(taskEntity);
    }

    @Override
    public void refuse(DelBody body) {
        ConfirmEntity confirmEntity = new ConfirmEntity();
        confirmEntity = confirmRepository.findOne(body.getId());
        confirmEntity.setRefused(1);
        confirmRepository.save(confirmEntity);
    }

    @Override
    public void refund(ConfirmRefundVo body) {

        ApplyEntity applyEntity = applyRepository.findOne(body.getApplyId());

        if (applyEntity.getRefund() == 1) {
            throw new CommonServiceException(ApiResponseCode.PERMISSION_DENIED.getCode(), "已申请退款，请勿重复点击");
        }
        applyEntity.setRefund(1);
        applyRepository.save(applyEntity);

        ConfirmEntity confirmEntity = null;
        if (body.getConfirmId() != null && !body.getConfirmId().isEmpty()) {
            confirmEntity = confirmRepository.findOne(body.getConfirmId());
            confirmEntity.setRefund(1);
            confirmEntity.setFinish(1);
            confirmRepository.save(confirmEntity);
        }

        TeacherEntity teacherEntity = teacherRepository.findOne(applyEntity.getPartyaId());
        teacherEntity.setMoney(teacherEntity.getMoney().add(applyEntity.getMoney()));

        teacherRepository.save(teacherEntity);

        TaskEntity taskEntity = taskRepository.findOne(applyEntity.getTaskId());
        // 甲方给乙方评论
//            commentService.addCommentToB(userId, commentAddVo);
        // 修改task状态
        taskEntity.setNowCount(taskEntity.getNowCount() + 1);
        // 修改task状态
        if (taskEntity.getNowCount() == taskEntity.getPartybCount()) {
            taskEntity.setStatus("FINISH");
        }
        taskEntity.setUpdateTime(new Date());
        taskRepository.save(taskEntity);

        // TODO: 扣分

        // TODO: 19/11/26  定时解除
        // finish自动解除
    }

    public void addCommentList(String taskId, String userId) {
        List<ApplyEntity> applyEntities = applyRepository.findByTaskIdAndStatus(taskId, 1);
        for (ApplyEntity applyEntity : applyEntities) {

            if (applyEntity.getRefund() == 1) {
                continue;
            }
            // confirm修改
            List<ConfirmEntity> confirmEntity = confirmRepository.findByTaskIdAndPartybIdOrderByCreateTimeDesc(taskId, applyEntity.getPartybId());

            if (confirmEntity != null && confirmEntity.size() > 0) {
                if (confirmEntity.get(0).getFinish() == 1) {
                    continue;
                }
            }
            TaskEntity taskEntity = taskRepository.findOne(applyEntity.getTaskId());
            // 甲方给乙方评论
            CommentAddVo commentAddVo = new CommentAddVo();
            commentAddVo.setContent("很棒，辛苦啦~");
            commentAddVo.setPoint(5.0);
            commentAddVo.setTaskId(taskId);
            commentAddVo.setReceiverId(applyEntity.getPartybId());
            commentAddVo.setType("PARTYA");
            commentService.addCommentToB(userId, commentAddVo);
            // 修改task状态
            taskEntity.setNowCount(taskEntity.getNowCount() + 1);
            // 修改task状态
            if (taskEntity.getNowCount() == taskEntity.getPartybCount()) {
                taskEntity.setStatus("FINISH");
            }
//            taskEntity.setStatus("FINISH");
            taskEntity.setUpdateTime(new Date());
            taskRepository.save(taskEntity);

            //确认完成增加积分
            PointEntity pointEntity = pointRepository.findByType("SUCCESS");
            int point = pointEntity.getValue();
            // 给乙方增加积分
            pointService.addPoint(applyEntity.getPartybId(), point);
            // 增加记录
            pointService.addUserPoint(applyEntity.getPartybId(), PointType.SUCCESS, point, "0");

            // TODO 打钱
//            ApplyEntity applyEntity = applyRepository.findByTaskIdAndPartybId(taskEntity.getId(), commentAddVo.getReceiverId());
            UserEntity userEntity = userRepository.findOne(applyEntity.getPartybId());
            // 扣除手续费
            PercentEntity percentEntity = percentRepository.findOne("percent001");
            userEntity.setMoney(userEntity.getMoney().add(applyEntity.getMoney().multiply(percentEntity.getPercent())));
            userRepository.save(userEntity);

            // confirm修改
            List<ConfirmEntity> confirmEntityList = confirmRepository.findByTaskIdAndPartybIdOrderByCreateTimeDesc(taskEntity.getId(), applyEntity.getPartybId());
            for (ConfirmEntity confirmEntity1 : confirmEntityList) {
                confirmEntity1.setFinish(1);
                confirmRepository.save(confirmEntity1);
            }
        }
    }


    @Override
    public void addComment(CommentAddVo commentAddVo, String userId) {

        // 甲方发出评论
        if ("PARTYA".equals(commentAddVo.getType())) {
            TaskEntity taskEntity = taskRepository.findOne(commentAddVo.getTaskId());
            if (!"BFINISH".equals(taskEntity.getStatus())) {
                throw new CommonServiceException(ApiResponseCode.PERMISSION_DENIED.getCode(), "接单方未点击完成，无法确认完成");
            }
            // 甲方给乙方评论
            commentService.addCommentToB(userId, commentAddVo);
            taskEntity.setNowCount(taskEntity.getNowCount() + 1);
            // 修改task状态
            if (taskEntity.getNowCount() == taskEntity.getPartybCount()) {
                taskEntity.setStatus("FINISH");
            }
            taskEntity.setUpdateTime(new Date());
            taskRepository.save(taskEntity);

            //确认完成增加积分
            PointEntity pointEntity = pointRepository.findByType("SUCCESS");
            int point = pointEntity.getValue();
            // 给乙方增加积分
            pointService.addPoint(commentAddVo.getReceiverId(), point);
            // 增加记录
            pointService.addUserPoint(commentAddVo.getReceiverId(), PointType.SUCCESS, point, "0");

            // TODO 打钱
            ApplyEntity applyEntity = applyRepository.findByTaskIdAndPartybId(taskEntity.getId(), commentAddVo.getReceiverId());
            UserEntity userEntity = userRepository.findOne(commentAddVo.getReceiverId());
            // 扣除手续费
            PercentEntity percentEntity = percentRepository.findOne("percent001");
            userEntity.setMoney(userEntity.getMoney().add(applyEntity.getMoney().multiply(percentEntity.getPercent())));
            userRepository.save(userEntity);

            // confirm修改
            List<ConfirmEntity> confirmEntity = confirmRepository.findByTaskIdAndPartybIdOrderByCreateTimeDesc(taskEntity.getId(), commentAddVo.getReceiverId());
            for (ConfirmEntity confirmEntity1 : confirmEntity) {
                confirmEntity1.setFinish(1);
                confirmRepository.save(confirmEntity1);
            }

        } else if ("PARTYB".equals(commentAddVo.getType())) {
            TaskEntity taskEntity = taskRepository.findOne(commentAddVo.getTaskId());
            if (!"FINISH".equals(taskEntity.getStatus())) {
                throw new CommonServiceException(ApiResponseCode.PERMISSION_DENIED.getCode(), "不是已完成状态，无法评价甲方");
            }
            // 乙方给甲方评论
            commentService.addCommentToA(userId, commentAddVo);
            taskEntity.setUpdateTime(new Date());
            taskEntity.setBcomment("1");
            taskRepository.save(taskEntity);
        }

    }

    @Transactional
    @Override
    public void del(DelBody id, String partyaId) {
        TaskEntity taskEntity = taskRepository.findOne(id.getId());
        taskRepository.delete(id.getId());
        applyRepository.deleteByTaskId(id.getId());
        List<CommentEntity>  commentEntities = commentRepository.findByTaskId(id.getId());
        for(CommentEntity commentEntity:commentEntities ) {
            commentRepository.delete(commentEntity.getId());
        }
        List<ConfirmEntity> confirmEntities = confirmRepository.findByTaskId(id.getId());
        for(ConfirmEntity confirmEntity:confirmEntities) {
            confirmRepository.delete(confirmEntity.getId());
        }
    }

    @Transactional
    @Override
    public void delList(DelListBody idList) {

    }

    @Override
    public void add(String partyaid, TaskAddVo taskAddVo) {
        TeacherEntity teacherEntity = teacherRepository.findOne(partyaid);
        if (teacherEntity == null) {
            throw new CommonServiceException(ApiResponseCode.PERMISSION_DENIED.getCode(), "请使用发布方账号发布任务");
        }
        //确认完成增加积分
        PointEntity pointEntity = pointRepository.findByType("PUBLISH");
        int point = pointEntity.getValue();

        // 群招扣除20分
        if (taskAddVo.getClassc().equals("群招")) {
            point = 20;
        }
        if(teacherEntity.getPoint() - point < 0) {
            throw new CommonServiceException(ApiResponseCode.USER_LOCKED.getCode(), "积分不足");
        }
        TaskEntity taskEntity =  new TaskEntity();
        taskEntity.setCreateTime(new Date());
        taskEntity.setUpdateTime(new Date());
        taskEntity.setPartyaId(partyaid);
        taskEntity.setTitle(taskAddVo.getTitle());
        taskEntity.setId(UUIDUtils.getUUID());
        taskEntity.setStatus("PRE");
        taskEntity.setClassc(taskAddVo.getClassc());
        taskEntity.setClassb(taskAddVo.getClassb());
        taskEntity.setClassa(taskAddVo.getClassa());
        taskEntity.setOnline(taskAddVo.getOnline());
        taskEntity.setSex(taskAddVo.getSex());
        taskEntity.setPrice(taskAddVo.getPrice());
        taskEntity.setLanguage(taskAddVo.getLanguage());
        taskEntity.setGrade(taskAddVo.getGrade());
        taskEntity.setCollege(taskAddVo.getCollege());
        taskEntity.setType(taskAddVo.getType());
        taskEntity.setStar(taskAddVo.getStar());
        taskEntity.setLocation(taskAddVo.getLocation());
        taskEntity.setTime(taskAddVo.getTime());
//        taskEntity.setDeadline(taskAddVo.getDeadline());
        taskEntity.setDeadline(0);
        taskEntity.setCount(taskAddVo.getCount());
        taskEntity.setRole(taskAddVo.getRole());
        taskEntity.setChinese(taskAddVo.getChinese());
        taskEntity.setEnv(taskAddVo.getEnv());
        taskEntity.setTSex(taskAddVo.getTSex());
        taskEntity.setDetail(taskAddVo.getDetail());
        taskEntity.setAddress(taskAddVo.getAddress());
        taskEntity.setLongitude(taskAddVo.getLongitude());
        taskEntity.setLatitude(taskAddVo.getLatitude());
        BeanUtils.copyProperties(taskAddVo, taskEntity);
        taskRepository.save(taskEntity);
        // 扣除积分
        pointService.delPointPartyA(teacherEntity, point);
        // 增加记录
        pointService.addUserPoint(partyaid, PointType.PUBLISH, point, "1");

    }

    @Override
    public void modify(TaskModVo taskModVo) {
        TaskEntity taskEntity = taskRepository.findOne(taskModVo.getId());
        if (taskEntity == null) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "没有对应信息");
        }
        taskEntity.setUpdateTime(new Date());
        taskEntity.setTitle(taskModVo.getTitle());
        taskEntity.setStatus(taskModVo.getStatus());
        taskEntity.setClassc(taskModVo.getClassc());
        taskEntity.setClassb(taskModVo.getClassb());
        taskEntity.setClassa(taskModVo.getClassa());
        taskEntity.setOnline(taskModVo.getOnline());
        taskEntity.setSex(taskModVo.getSex());
        taskEntity.setPrice(taskModVo.getPrice());
        taskEntity.setLanguage(taskModVo.getLanguage());
        taskEntity.setGrade(taskModVo.getGrade());
        taskEntity.setCollege(taskModVo.getCollege());
        taskEntity.setType(taskModVo.getType());
        taskEntity.setStar(taskModVo.getStar());
        taskEntity.setLocation(taskModVo.getLocation());
        taskEntity.setTime(taskModVo.getTime());
        taskEntity.setCount(taskModVo.getCount());
        taskEntity.setRole(taskModVo.getRole());
        taskEntity.setChinese(taskModVo.getChinese());
        taskEntity.setEnv(taskModVo.getEnv());
        taskEntity.setTSex(taskModVo.getTSex());
        taskEntity.setDetail(taskModVo.getDetail());
        taskRepository.save(taskEntity);
    }

    @Override
    public TaskDetailAVo getTaskDetail(String id, UserInfo userInfo, double longitude, double latitude){
        TaskDetailAVo taskDetailAVo = new TaskDetailAVo();
        TaskEntity taskEntity = taskRepository.findOne(id);
        TaskDetailVo taskDetailVo = new TaskDetailVo();

         if(taskEntity != null) {
             BeanUtils.copyProperties(taskEntity, taskDetailVo);

             if(userInfo != null && "PARTYB".equals(userInfo.getType())) {
                 String partybid = userInfo.getId();
                 ApplyEntity applyEntity = applyRepository.findByTaskIdAndPartybId(id, partybid);
                 if(applyEntity != null) {
                     taskDetailVo.setApplied("1");
                 } else {
                     taskDetailVo.setApplied("0");
                 }

                 ApplyEntity applyEntity1 = applyRepository.findByTaskIdAndPartybIdAndStatus(id, partybid, 1);

                 if (applyEntity1 != null) {
                     taskDetailVo.setIsPartyBOwner("1");
                 } else {
                     taskDetailVo.setIsPartyBOwner("0");
                 }

             } else if (userInfo != null && "PARTYA".equals(userInfo.getType())){
                 if (userInfo.getId().equals(taskEntity.getPartyaId())) {
                     taskDetailVo.setIsPartyAOwner("1");
                 } else {
                     taskDetailVo.setIsPartyAOwner("0");
                 }
             }

             String distance = algorithm(taskEntity.getLongitude(), taskEntity.getLatitude(), longitude, latitude);
             taskDetailVo.setDistance(distance);

             if ("ONLINE".equals(taskEntity.getStatus()) || "BFINISH".equals(taskEntity.getStatus()) || "FINISH".equals(taskEntity.getStatus())) {

                 List<ConfirmEntity> confirmEntities = confirmRepository.findByTaskIdOrderByCreateTimeDesc(taskEntity.getId());
                 if (confirmEntities != null && confirmEntities.size() > 0) {
                     taskDetailAVo.setConfirmEntity(ListUtils.getFirst(confirmEntities));
                 }
             }
         }

        taskDetailAVo.setTaskDetailVo(taskDetailVo);

        UserSimpleInfoVo partaSimpleInfoVo = userService.getUserById(taskEntity.getPartyaId(), "PARTYA");
        taskDetailAVo.setPartaSimpleInfoVo(partaSimpleInfoVo);

        return  taskDetailAVo;

    }

    @Override
    public ConfirmListVo confirmList(String taskId){
        ConfirmListVo confirmListVo = new ConfirmListVo();
        List<ConfirmEntity> confirmEntities = confirmRepository.findByTaskIdOrderByCreateTimeDesc(taskId);
        confirmListVo.setTotalCount(confirmEntities.size());
        confirmListVo.setList(confirmEntities);
        return  confirmListVo;
    }

    public static String algorithm(double longitude1, double latitude1, double longitude2, double latitude2) {

        double Lat1 = rad(latitude1); // 纬度

        double Lat2 = rad(latitude2);

        double a = Lat1 - Lat2;//两点纬度之差

        double b = rad(longitude1) - rad(longitude2); //经度之差

        double s = 2 * Math.asin(Math

                .sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));//计算两点距离的公式

        s = s * 6378137.0;//弧长乘地球半径（半径为米）

        s = Math.round(s * 10000d) / 10000d;//精确距离的数值
        s = s/1000;//将单位转换为km，如果想得到以米为单位的数据 就不用除以1000
        //四舍五入 保留一位小数
        DecimalFormat df = new DecimalFormat("0.##");

        return df.format(s);

    }

    public static List<TaskVo> pageBySubList(List<TaskVo> list, int pagesize, int curPage) {
        int currentPage = curPage+1;
        List<TaskVo> subList =new ArrayList<>();
        int size=list.size();
        int pageStart = currentPage==1 ? 0 : (currentPage-1) * pagesize;
        int pageEnd = size < currentPage*pagesize ? size : currentPage*pagesize;
        if(size >  pageStart) {
            subList = list.subList(pageStart, pageEnd);
        }
        return subList;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.00; //角度转换成弧度
    }
}
